import { wxlogin, getInfo, updateUserInfo } from '../../services/profile'
import { queryVehicle } from '../../services/vehicle'
import Toast from '@vant/weapp/toast/toast';
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    loginCode:"",
    wxUserInfo:{},
    userInfo:{},
    hasUserInfo:false,
    vehicleNum: 0,
    sectionList1:[
      {
        name:'我的车辆',
        url:'/pages/my-vehicle/my-vehicle',
        type:'page'
      },
      {
        name:'我的报告',
        url:'/pages/inspection-report/inspection-report',
        type:'tabbar'
      }
    ],
    sectionList2:[
      {
        name:'帮助文档',
        url:'/pages/policy-agreement/policy-agreement?type=guide',
        type:'page'
      },
      {
        name:'用户协议',
        url:'/pages/policy-agreement/policy-agreement?type=agreement',
        type:'page'
      },
      {
        name:'隐私政策',
        url:'/pages/policy-agreement/policy-agreement?type=policy',
        type:'page'
      }
    ],
    sectionList3:[
      // {
      //   name:'账号安全',
      //   url:'',
      //   type:'page'
      // },
      {
        name:'切换账号',
        url:'/pages/user-info/user-info',
        type:'page'
      },
      {
        name:'注销账号',
        url:'/pages/deregister/deregister',
        type:'page'
      }
    ],
    isLogin: false,
    token: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.getCode()
  },

  onShow(){
    this.setData({
      token: wx.getStorageSync('token')
    })
    this.getCode()
    this.getUserInfo()
    this.handleQueryVehicle()
    // const tempUserInfo = app.globalData.userInfo || wx.getStorageSync('userInfo') || {}
    // if(!(app.globalData.userInfo || wx.getStorageSync('userInfo'))){
    //   this.setData({
    //     isLogin: false
    //   })
    // }else{
    //   this.setData({
    //     isLogin: true
    //   })
    // }
  },

  getCode(){
    let token = wx.getStorageSync('token')
    if(!token){
      wx.login({
        success: res => {
          console.log("profile>loginRes>>>", res)
          wx.setStorageSync('code', res.code)
        }
      })
    }
  },

  getPhoneNumber (e) {
    const code = wx.getStorageSync('code') || ""
    const encryptedData = e.detail.encryptedData
    const iv = e.detail.iv
    
    wxlogin({code, encryptedData, iv, type:"0"}).then(res => {
      console.log("loginRes>>>",res)
      if(res.code === 200){
        const token = res.data.access_token
        wx.setStorageSync('token', token)
        getInfo().then(InfoRes=>{
          console.log("InfoRes>>>", InfoRes)
          if(InfoRes.code === 200){
            this.setData({
              userInfo: InfoRes.user
            })
            wx.setStorageSync('userInfo', InfoRes.user)
            app.globalData.userInfo = InfoRes.user
          }
        })
      }
    })
  },

  handleViewOrder(){
    wx.navigateTo({
      url: '/pages/order-list/order-list?tabIndex=all',
    })
  },

  handleSetWxInfo(){
    this.getUserProfile()
  },

  handleSwitchUser(){
    wx.navigateTo({
      url: '/pages/personal-info/personal-info',
    })
  },

  async getUserInfo(){
    let token = wx.getStorageSync('token')
    if(token){
      let userRes = await getInfo()
      if(userRes.code === 401 && userRes.msg == '登录状态已过期'){
        Toast.fail('登录状态已过期,请重新登录!');
        app.globalData.userInfo = null
        // wx.removeStorageSync('token')
        // wx.removeStorageSync('userInfo')
        // wx.removeStorageSync('appid')
        // wx.removeStorageSync('secret')
        // if(wx.getStorageSync('spaceId')){
        //   wx.removeStorageSync('spaceId')
        // }
        wx.clearStorage()
        this.setData({
          userInfo: {},
          isLogin: false
        })
        this.getCode()
      }
      if(userRes.code === 200){
        let tempUserInfo = userRes.user

        this.setData({
          isLogin: true
        })
        if(tempUserInfo.avatarUrl || tempUserInfo.avatar){
          this.setData({
            hasUserInfo: true
          })
        } else {
          this.setData({
            hasUserInfo: false
          })
        }
    
        this.setData({
          userInfo: tempUserInfo
        })
      }
    } else {
      this.setData({
        userInfo: {},
        isLogin: false
      })
    }
  },

  clickToLogin(){
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },

  getUserProfile() {
    console.log("112212")
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
    // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '用于完善个人信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log("res>>>", res)
        let userInfo = {...this.data.userInfo, ...res.userInfo}
        app.globalData.userInfo = userInfo
        this.setData({
          userInfo,
          hasUserInfo: true
        })
        this.handleUpdateInfo()
      }
    })
  },

  async handleUpdateInfo(){
    let userId = this.data.userInfo.userId
    let avatar = this.data.userInfo.avatarUrl || ""
    let nickName = this.data.userInfo.nickName
    let userName = this.data.userInfo.userName
    let res = await updateUserInfo({
      userId,
      avatar,
      nickName,
      userName
    })
    console.log("res>>>", res)
  },

  async handleQueryVehicle(){
    let resVehicle = await queryVehicle()    
    if(resVehicle.code === 200){
      let vehicleNum = resVehicle.total
      this.setData({
        ['sectionList1[0].name']: `我的车辆 (${vehicleNum}辆)`
      })
    }
  }
})